package com.day12.study.chat;

import java.io.*;
import java.net.Socket;
import java.util.List;

/**
 * 客户端连接成功后，启动此子线程来进行与客户端的交互
 */
public class ServerThread implements Runnable {

    private Socket socket;
    List<Socket> socketList;

    public ServerThread(Socket socket, List<Socket> list) {
        super();
        this.socket = socket;
        this.socketList = list;
    }

    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();
            DataInputStream dis = new DataInputStream(is);
            DataOutputStream dos = new DataOutputStream(os);
            String receiveMsg = null;
            dos.writeUTF("欢迎：" + socket.getRemoteSocketAddress());
            do {
                receiveMsg = dis.readUTF();
                for (Socket s : socketList) {
                    OutputStream outputStream = s.getOutputStream();
                    DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
                    dataOutputStream.writeUTF(receiveMsg);
                    outputStream.close();
                    dataOutputStream.close();
                }
                dos.writeUTF("来自服务端：" + receiveMsg);
            } while (!"再见".equals(receiveMsg));
            dis.close();
            dos.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            socketList.remove(socket);
        }
    }
}
